package com.neuedu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neuedu.common.JSONData;
import com.neuedu.dao.*;
import com.neuedu.pojo.*;
import com.neuedu.service.OrderService;
import com.neuedu.utils.BigDecimalUtil;
import com.neuedu.vo.OrderVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(value = "orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductSKUMapper productSKUMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ShippingMapper shippingMapper;

    public JSONData createOrder(Integer userId, Integer shippingId) {
        //-1、从购物车中获取已勾选的商品
        List<Cart> cartList = cartMapper.queryCheckedCartByUserId(userId);
        if(cartList==null){
            return JSONData.buildError("购物车为选中任何商品，请重新核对");
        }
        //-2、判断商品的合法性 例如：商品是否在售，是否超出库存 等
        //	并生成订单明细
        JSONData data = checkCartProduct(userId,cartList);
        if(data.getCode()!=0){
            return data;
        }
        //-订单明细
        List<OrderItem> orderItemList = (List<OrderItem>) data.getData();
        //-3、生成订单总金额
        BigDecimal orderTotalPrice = orderTotalPrice(orderItemList);
        //-4、生成订单
        Order order = newOrder(userId,shippingId,orderTotalPrice);
        int num = orderMapper.insert(order);
        if(num<=0){
            return JSONData.buildError("订单创建失败");
        }
        //-5、将订单号，放入到订单明细中
        for(OrderItem orderItem:orderItemList){
            orderItem.setOrderNo(order.getOrderNo());
        }
        //-6、批量插入订单明细
        num = orderItemMapper.batchInsert(orderItemList);
        if(num<=0){
            return JSONData.buildError("订单明细创建失败");
        }
        //-7、减少商品库存的数量
        for(OrderItem orderItem:orderItemList){
            ProductSKU productSKU = productSKUMapper.selectByPrimaryKey(orderItem.getProductId());
            productSKU.setStock(productSKU.getStock()-orderItem.getQuantity());
            productSKUMapper.updateByPrimaryKey(productSKU);
        }
        //-8、清空购物车被选中的商品
        for(Cart cart:cartList){
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
        //-9、返回前端的信息（订单所有的信息：订单、订单明细、收货地址）=>OrderVo
            //-生成订单明细
           JSONData<OrderVo> data_1 = orderDetail(userId,order.getOrderNo());

        return data_1;
    }
    //-判断商品的合法性 例如：商品是否在售，是否超出库存==>并生成订单明细
    private JSONData checkCartProduct(Integer userId,List<Cart> cartList){
        List<OrderItem> orderItemList = new ArrayList<OrderItem>();
        //-遍历商品集合
        for(Cart cart:cartList){
            //-查看 商品信息：SKU ==>库存
            ProductSKU productSKU = productSKUMapper.selectByPrimaryKey(cart.getProductId());
            //-商品信息：SPU ==》状态
            Product product = productMapper.selectByPrimaryKey(productSKU.getProductId());

            if(product.getStatus()!=1){
                return JSONData.buildError(product.getName()+"已不是在售状态");
            }
            if(cart.getQuantity()>productSKU.getStock()){
                return JSONData.buildError(product.getName()+"库存不足");
            }
            //--讲此商品生成订单明细
            OrderItem orderItem = new OrderItem();
            orderItem.setUserId(userId);
            orderItem.setProductId(productSKU.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(productSKU.getSellprice());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setTotalPrice(BigDecimalUtil.mul(productSKU.getSellprice().doubleValue(),cart.getQuantity().doubleValue()));

            orderItemList.add(orderItem);
        }
        return JSONData.buildSuccess(orderItemList);
    }
    //生成订单总金额
    private BigDecimal orderTotalPrice(List<OrderItem> orderItemList){
        BigDecimal totalPrice = new BigDecimal("0");
        for(OrderItem orderItem:orderItemList){
            totalPrice = BigDecimalUtil.add(totalPrice.doubleValue(),orderItem.getTotalPrice().doubleValue());
        }
        return totalPrice;
    }
    //-生成订单
    private Order newOrder(Integer userId,Integer shippingId,BigDecimal totalPrice){
        Order order = new Order();
        order.setOrderNo(createOrderNo());
        //-未付款
        order.setStatus(10);
        order.setPostage(0);
        order.setPaymentType(1);
        order.setPayment(totalPrice);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        return order;
    }
    private Long createOrderNo(){
        return System.currentTimeMillis();
    }
    //-生成订单明细
    public JSONData<OrderVo> orderDetail(Integer userId,Long orderNo){
        OrderVo orderVo = new OrderVo();
        //-判断订单号是否存在
        Order order = orderMapper.selOrderByUserIdAndOrderNo(userId, orderNo);
        if(order==null){
            return JSONData.buildError("订单号不存在");
        }
        //-将订单的信息 赋值 给订单的扩展类
        BeanUtils.copyProperties(order,orderVo);
        //-根据订单号，查询订单明细
        List<OrderItem> orderItemList = orderItemMapper.queryOrderItemsByUserIdAndOrderNo(userId, orderNo);
        orderVo.setOrderItemList(orderItemList);
        //-收货地址
        Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
        orderVo.setShipping(shipping);
        return JSONData.buildSuccess(orderVo);
    }

    public JSONData<PageInfo<OrderVo>> orderList(Integer userId, int pageNum, int pageSize) {
        List<OrderVo> orderVoList = new ArrayList<OrderVo>();
        //-1、查询所有的订单：
        List<Order> orders = orderMapper.queryAllOrderByUserId(userId);
        OrderVo orderVo = null;
        for(Order order:orders){
            orderVo = new OrderVo();
            //-将订单的信息（order） 赋值到 订单的扩展类上（orderVo）
            BeanUtils.copyProperties(order,orderVo);
            //-订单明细
            List<OrderItem> orderItemList = orderItemMapper.queryOrderItemsByUserIdAndOrderNo(userId, order.getOrderNo());
            orderVo.setOrderItemList(orderItemList);
            //-收货地址
            Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
            orderVo.setShipping(shipping);
            orderVoList.add(orderVo);
        }
        //-PageHelper 分页
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<OrderVo> pageInfo = new PageInfo<OrderVo>(orderVoList);
        pageInfo.setList(orderVoList);
        return JSONData.buildSuccess(pageInfo);
    }

    public JSONData<String> cancel(Integer userId, Long orderNo) {
        //-1、订单是否存在
        Order order = orderMapper.selOrderByUserIdAndOrderNo(userId, orderNo);
        if(order==null){
            return JSONData.buildError("此订单不存在");
        }
        //-2、将订单的状态，改为取消订单
        order.setStatus(0);
        int num = orderMapper.updateByPrimaryKey(order);
        if(num<=0){
            return JSONData.buildError("订单取消失败");
        }
        //-3、商品对应的库存需要增加
        List<OrderItem> orderItemList = orderItemMapper.queryOrderItemsByUserIdAndOrderNo(userId, order.getOrderNo());
        for(OrderItem orderItem:orderItemList){
            int productId = orderItem.getProductId();
            int quantity = orderItem.getQuantity();
            //-查询商品信息
            ProductSKU productSKU = productSKUMapper.selectByPrimaryKey(productId);
            productSKU.setStock(BigDecimalUtil.add(productSKU.getStock().doubleValue(),orderItem.getQuantity().doubleValue()).intValue());
            num = productSKUMapper.updateByPrimaryKey(productSKU);
            if(num<=0){
                break;
            }
        }
        if(num>0){
            return JSONData.buildSuccess("订单取消成功");
        }else{
            return JSONData.buildError("订单取消失败");
        }
    }

    public JSONData<String> sendOrder(Long orderNo) {
        //-查询订单是否存在
        Order order = orderMapper.selOrderByUserIdAndOrderNo(null,orderNo);
        if(order==null){
            return JSONData.buildError("此订单号，不存在");
        }
        //-修改订单的状态：orderNo=》status、send_time
        int num = orderMapper.updateOrderStatusAndSendTimeByOrderNo(orderNo,30,new Date());
        if(num>0){
            return JSONData.buildSuccess("发货成功！");
        }else{
            return JSONData.buildError("发货失败!");
        }
    }
}
